package com.vc.commons.response;

import java.lang.reflect.Type;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.vc.commons.model.BaseResponse;

/**
 * response的统一处理
 * @author Cris
 *
 */
@RestControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice<Object> {
	
	@Autowired
	private BaseResponse<Object> baseResponse;

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		// 如果返回true继续执行，false不向下执行
		
		//ParameterizedType parameterizedType = (ParameterizedType) returnType.getGenericParameterType();
		//Type type = parameterizedType.getRawType();
		// type是Class类型的对象
		converterType.isAssignableFrom(BaseResponse.class);
		Type type = returnType.getMethod().getReturnType();
		return type == BaseResponse.class ? false : true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		baseResponse.setData(body);
		return baseResponse;
	}

}
